package com.duoduo.demo.rabbitmq.rpc;

import java.util.Date;

import javax.annotation.Resource;

import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class RabbitmqRpcClient {

	@Value("${rmq.rpc.exchange}")
	private String rpcExchangeName = "demo.rpc.ex";
	@Value("${rmq.rpc.routingkey}")
	private String rpcRoutingKey = "demo.rpc.k";
	@Value("${rmq.rpc.requestqueue}")
	private String rpcRequestQueue = "demo.rpc.q";
	@Value("${rmq.rpc.replyqueue}")
	private String rpcReplyQueue = "demo.rpc.r";

	@Resource(name = "requestRabbitTemplate")
	private AmqpTemplate rabbitTemplate;

	@RabbitListener(queues = "${rmq.rpc.replyqueue}")
	public void process(Message message) {
		System.out.println("[CLIENT]Return RPC: " + message.toString());
		if (message == null || message.getBody() == null || message.getMessageProperties() == null) {
			System.out.println("[CLIENT]	Message is invalid");
			return;
		}

		String replyTo = message.getMessageProperties().getReplyTo();
		System.out.println("[CLIENT]	RPC replyTo: " + replyTo);

		String data = "result: " + message.getBody().toString();
		System.out.println("[SERVER]	RPC data: " + data);
	}

	public void send() {
		String context = "hello " + new Date();
		// System.out.println("Sender : " + context);
		// System.out.println(" Exchange : " + rpcExchangeName);
		// System.out.println(" RoutingKey : " + rpcRoutingKey);
		//
		// String requestId = UUID.randomUUID().toString();
		// MessageProperties mp = new MessageProperties();
		// mp.setMessageId(requestId);
		// mp.setCorrelationIdString(requestId);
		// // mp.setReplyTo(rpcReplyQueue);
		// System.out.println("Send MessageProperties : " + mp.toString());
		//
		// Message message = new Message(context.getBytes(), mp);
		// System.out.println("Send Message : " + message.toString());
		//
		// // Object result = rabbitTemplate.convertAndSend(rpcExchangeName, rpcRoutingKey, message);
		// // System.out.println("[CLIENT]Receiver RPC: " + result.toString());
		//
		// // rabbitTemplate.convertAndSend(rpcExchangeName, rpcRoutingKey, context);
		//
		// // rabbitTemplate.convertAndSend(rpcExchangeName, rpcRoutingKey, message);
		// // rabbitTemplate.send(rpcExchangeName, rpcRoutingKey, message);
		//
		// Message result = rabbitTemplate.sendAndReceive(rpcExchangeName, rpcRoutingKey, message, new
		// CorrelationData(requestId));
		// System.out.println("[CLIENT]Receiver result: " + result.toString());

		Object result = rabbitTemplate.convertSendAndReceive(rpcExchangeName, rpcRoutingKey, context);
		System.out.println("[CLIENT]Receiver result: " + result.toString());
	}

}
